import 'package:flutter/material.dart';
import 'package:uuid/uuid.dart';
import '../constants/themes.dart';
import '../models/question.dart';

class AppState extends ChangeNotifier {
  final Uuid _uuid = const Uuid();

  // 主题状态
  ThemeType _currentTheme = ThemeType.green;
  ThemeType get currentTheme => _currentTheme;

  // 当前页面索引 (0: 导语, 1: 基本信息, 2: SCL-90问卷, 3: 结果)
  int _currentPageIndex = 0;
  int get currentPageIndex => _currentPageIndex;

  // 基本信息
  BasicInfo? _basicInfo;
  BasicInfo? get basicInfo => _basicInfo;

  // SCL-90问卷答案 (题目ID -> 分数1-5)
  Map<int, int> _sclAnswers = {};
  Map<int, int> get sclAnswers => _sclAnswers;

  // 分析结果
  String? _analysisResult;
  String? get analysisResult => _analysisResult;

  // 测试ID
  String? _testId;
  String? get testId => _testId;

  // 是否正在加载
  bool _isLoading = false;
  bool get isLoading => _isLoading;

  // 当前SCL-90问题索引
  int _currentSCLQuestionIndex = 0;
  int get currentSCLQuestionIndex => _currentSCLQuestionIndex;

  // 切换主题
  void changeTheme(ThemeType theme) {
    _currentTheme = theme;
    notifyListeners();
  }

  // 设置当前页面
  void setCurrentPage(int index) {
    _currentPageIndex = index;
    notifyListeners();
  }

  // 保存基本信息
  void saveBasicInfo(
    String age,
    String gender,
    String occupation,
    String sleepCondition,
  ) {
    _basicInfo = BasicInfo(
      age: age,
      gender: gender,
      occupation: occupation,
      sleepCondition: sleepCondition,
    );
    notifyListeners();
  }

  // 保存SCL-90答案
  void saveSCLAnswer(int questionId, int score) {
    _sclAnswers[questionId] = score;
    notifyListeners();
  }

  // 获取SCL-90答案
  int? getSCLAnswer(int questionId) {
    return _sclAnswers[questionId];
  }

  // 设置当前SCL-90问题索引
  void setCurrentSCLQuestionIndex(int index) {
    _currentSCLQuestionIndex = index;
    notifyListeners();
  }

  // 开始新的测试
  void startNewTest() {
    _testId = _uuid.v4();
    _basicInfo = null;
    _sclAnswers.clear();
    _analysisResult = null;
    _currentPageIndex = 0;
    _currentSCLQuestionIndex = 0;
    notifyListeners();
  }

  // 设置分析结果
  void setAnalysisResult(String result) {
    _analysisResult = result;
    notifyListeners();
  }

  // 设置测试ID
  void setTestId(String testId) {
    _testId = testId;
    notifyListeners();
  }

  // 设置加载状态
  void setLoading(bool loading) {
    _isLoading = loading;
    notifyListeners();
  }

  // 检查基本信息是否完整
  bool isBasicInfoComplete() {
    return _basicInfo != null;
  }

  // 检查是否完成所有SCL-90问题
  bool isAllSCLQuestionsAnswered() {
    return _sclAnswers.length >= 90;
  }

  // 获取SCL-90完成进度
  double getSCLProgress() {
    return _sclAnswers.length / 90.0;
  }

  // 获取当前阶段描述
  String getCurrentStageDescription() {
    switch (_currentPageIndex) {
      case 0:
        return '测试说明';
      case 1:
        return '基本信息';
      case 2:
        return 'SCL-90问卷';
      case 3:
        return '测试结果';
      default:
        return '未知阶段';
    }
  }

  // 获取总体进度
  double getTotalProgress() {
    switch (_currentPageIndex) {
      case 0:
        return 0.0;
      case 1:
        return isBasicInfoComplete() ? 0.2 : 0.1;
      case 2:
        return 0.2 + (getSCLProgress() * 0.7);
      case 3:
        return 1.0;
      default:
        return 0.0;
    }
  }

  // 重置状态
  void reset() {
    _basicInfo = null;
    _sclAnswers.clear();
    _analysisResult = null;
    _testId = null;
    _currentPageIndex = 0;
    _currentSCLQuestionIndex = 0;
    _isLoading = false;
    notifyListeners();
  }

  // 获取完整的测试数据用于提交
  Map<String, dynamic> getCompleteTestData() {
    return {
      'test_id': _testId,
      'basic_info': _basicInfo?.toJson(),
      'scl_answers': _sclAnswers,
      'timestamp': DateTime.now().toIso8601String(),
    };
  }

  // 获取提交给API的数据格式
  Map<String, dynamic> getSubmissionData() {
    return {
      'basic_info': _basicInfo?.toJson(),
      'scl_answers': _sclAnswers.map(
        (key, value) => MapEntry(key.toString(), value),
      ),
    };
  }

  // 计算SCL-90因子得分
  Map<String, double> calculateSCLTotalScore() {
    double totalScore = 0;
    int answeredCount = 0;
    for (int i = 1; i <= 90; i++) {
      if (_sclAnswers.containsKey(i)) {
        totalScore += _sclAnswers[i]!;
        answeredCount++;
      }
    }
    return {
      '总分': answeredCount > 0 ? totalScore : 0.0,
      '平均分': answeredCount > 0 ? totalScore / answeredCount : 0.0,
    };
  }
}
